package cn.demoncat.test;

import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;

/**
 * 分片算法《列值类型》
 *
 * StandardShardingAlgorithm：STANDARD单列
 *
 * ComplexKeysShardingAlgorithm：COMPLEX多列
 */
public class TbAlgorithm implements StandardShardingAlgorithm<Integer>, ComplexKeysShardingAlgorithm<Integer> {

    private Properties props;

    /**
     * 执行分片（STANDARD单列，精确分片）
     *
     * @param collection    所有库（分库策略）/表（分表策略）
     * @param preciseShardingValue  当前数据：logicTableName = 逻辑表名，columnName = 列名，value = 列值
     * @return  根据当前数据，筛选指定的库/表
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Integer> preciseShardingValue) {
        return new ArrayList<>(collection).get(preciseShardingValue.getValue() % Integer.parseInt(props.getProperty("count")));
    }

    /**
     * 执行分片（STANDARD单列，范围分片）
     */
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Integer> rangeShardingValue) {
        // 可能同时落在多个库/表中
        return collection;
    }

    /**
     * 执行分片（COMPLEX多列，精确+范围分片）
     */
    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<Integer> complexKeysShardingValue) {
        // 可能同时落在多个库/表中
        return collection;
    }

    /**
     * 读取自定义属性
     *
     * spring.shardingsphere.rules.sharding.sharding-algorithms.算法名.props.自定义属性=属性值
     *
     * @param properties
     */
    @Override
    public void init(Properties properties) {
        this.props = properties;
    }

    /**
     * 获取自定义属性
     */
    @Override
    public Properties getProps() {
        return this.props;
    }
}
